package com.backend.controller;

import jakarta.servlet.http.HttpServletRequest;
import com.backend.anno.Log;
import com.backend.entity.*;
import com.backend.service.UserService;
import com.backend.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;


    @Autowired
    private StringRedisTemplate redisTemplate;

    //注册
    @PostMapping("/register")
    public Result registerUser(
            @RequestParam("username") String username,
            @RequestParam("password") String password
    ) {
        User user = userService.findByUsername(username);
        if (user == null) {
            userService.register(username,password);
            return Result.success();
        }else{
            return Result.error("用户名已被占用");
        }
    }

    //登录 向前端发送token 后续考虑增加redis进行缓存
    @PostMapping("/login")
    public Result<String> Login(
            @RequestParam("username") String username,
            @RequestParam("password") String password
    ){
        log.info("用户"+username+"登录");
        User user = userService.findByUsername(username);
        if(user==null){
            return Result.error("用户不存在");
        }
        if(password.equals(user.getPassword())){
            //jwt令牌：三部分 header（记录令牌类型 签名算法） PayLoad（记录自定义信息） Signatu（签名，防止被篡改）
            Map<String, Object> claims = new HashMap<>();
            claims.put("id",user.getId());
            claims.put("username",user.getUsername());
            String token = JwtUtil.genToken(claims);
            //把token储存到redis中
            ValueOperations<String, String> ops = redisTemplate.opsForValue();
            ops.set("token",token,1, TimeUnit.HOURS);
            return Result.success(token);
        }

        return Result.error("密码错误");
    }

    //修改用户名
    @Log
    @PutMapping("/update")
    public Result updateUser(
            @RequestParam("usernameBefore") String usernameBefore,
            @RequestParam("usernameAfter") String usernameAfter,
            HttpServletRequest request
    ){
        //从token中获取对应的请求用户名
        String token = request.getHeader("Authorization");
        Map<String, Object> claims = JwtUtil.parseToken(token);
        String username = (String) claims.get("username");
        Integer userId = (Integer) claims.get("id");
        //查询发出请求的用户身份
        User user = userService.findById(userId);
        Integer identity = user.getAdmin();
        if(identity==1 || Objects.equals(username, usernameBefore)){
            if (Objects.equals(usernameAfter, usernameBefore)){
                userService.updateByUsername(usernameBefore,usernameAfter);
                return Result.success("修改成功");
            }
            else if (userService.usernameExist(usernameAfter)!=0){
                return Result.error("用户名已被占用");
            }else{
                userService.updateByUsername(usernameBefore,usernameAfter);
                return Result.success("修改成功");
            }
        }else {
            return Result.error("当前用户无权限修改用户信息");
        }

    }

    //直接获取当前登录用户的全部信息
    @Log
    @GetMapping("/userdetail")
    public Result<User> userDetail(
            HttpServletRequest request
    ){
        //从token中获取对应的请求用户名
        String token = request.getHeader("Authorization");
        Map<String, Object> claims = JwtUtil.parseToken(token);
        Integer userId = (Integer) claims.get("id");
        User user = userService.findById(userId);
        return Result.success(user);
    }

    //更新密码
    @Log
    @PatchMapping("/updatePwd")
    public Result updatePwd(
            @RequestParam("id") Integer id,
            @RequestParam("newPassword") String newPassword,
            HttpServletRequest request
    ){
        //从token中获取对应的请求用户名
        String token = request.getHeader("Authorization");
        Map<String, Object> claims = JwtUtil.parseToken(token);
        Integer userId = (Integer) claims.get("id");
        User user = userService.findById(userId);
        Integer identity = user.getAdmin();
        if(newPassword.equals(user.getPassword())){
            return Result.error("新密码和旧密码相同");
        }
        if(identity==1 || Objects.equals(id, userId)){
            //更新用户密码
            userService.updatePwd(id,newPassword);
            //删除redis中对应token
            ValueOperations<String, String> ops = redisTemplate.opsForValue();
            ops.getOperations().delete("token");
            return Result.success();
        }else {
            return Result.error("该用户没有修改的权限");
        }
    }

    //退出登录
    @Log
    @PostMapping("/quit")
    public Result quit(
            HttpServletRequest request
    ){
        //从redis中删除对应token
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        ops.getOperations().delete("token");
        return Result.success("已退出");
    }


    //管理员查看全部用户 分页
    @Log
    @GetMapping("/listAll")
    public Result<PageBean> getAllUsers(
            @RequestParam Integer pageNumber,
            @RequestParam Integer pageSize,
            HttpServletRequest request
    ){
        PageBean pageBean = new PageBean();
        //从token中获取对应的请求用户id
        String token = request.getHeader("Authorization");
        Map<String, Object> claims = JwtUtil.parseToken(token);
        Integer userId = (Integer) claims.get("id");
        User user = userService.findById(userId);
        Integer identity = user.getAdmin();
        if(identity==1) {
            List<User> usersList = userService.listAll(pageNumber,pageSize);
            pageBean.setItems(usersList);
            pageBean.setCurrentPage(pageNumber);
            pageBean.setPages((int) (userService.listAllNum()/pageSize));
            pageBean.setTotal(userService.listAllNum());
            return Result.success(pageBean);
        }else {
            return Result.error("用户没有该权限");
        }
    }

    //管理员删除用户
    @Log
    @DeleteMapping()
    public Result getAllUsers(
            @RequestParam("deleteId") Integer deleteId,
            HttpServletRequest request
    ){
        //从token中获取对应的请求用户id
        String token = request.getHeader("Authorization");
        Map<String, Object> claims = JwtUtil.parseToken(token);
        Integer userId = (Integer) claims.get("id");
        User user = userService.findById(userId);
        Integer identity = user.getAdmin();
        if(identity==1) {
            userService.deleteUser(deleteId);
            return Result.success("删除成功");
        }else {
            return Result.error("用户没有该权限");
        }

    }

}
